#!/usr/bin/env python3
# coding=utf-8
import logging
import os
import time


class LoggerFactory:

    @staticmethod
    def get_logger(name: str, level: int = logging.DEBUG):
        # 创建一个自定义的logger
        custom_logger = logging.getLogger(name)
        custom_logger.setLevel(level)

        # 指定log文件存储路径
        filename = 'log_' + time.strftime('%y%m%d%H%M%S') + '.log'
        filepath = os.path.join(os.path.abspath(__file__), '..', 'logs', filename)

        # 创建一个handler，用于输出到文件
        file_handler = logging.FileHandler(filepath, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)

        # 创建一个handler，用于输出到控制台
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)

        # 创建一个格式器，包含模块名、行号等信息
        fmt = '%(asctime)s p%(process)d [%(levelname)3s] %(module)s::%(funcName)s %(lineno)d: %(message)s'
        formatter = logging.Formatter(fmt)
        file_handler.setFormatter(formatter)

        try:
            colorlog = __import__('colorlog')
            formatter = colorlog.ColoredFormatter('%(log_color)s' + fmt, log_colors={
                'DEBUG': 'white',
                'INFO': 'green',
                'WARNING': 'yellow',
                'ERROR': 'red,bold',
                'CRITICAL': 'light_white,bold,bg_red'})

        except ImportError:
            pass

        console_handler.setFormatter(formatter)
        custom_logger.addHandler(file_handler)
        custom_logger.addHandler(console_handler)

        return custom_logger


logger = LoggerFactory.get_logger('')
